<?php


namespace app\superpartner\controller;

use app\common\controller\CommonService;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Validate;
use think\Request;

class SetUp extends Controller
{
    /**
     *超级合伙人资料
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSuperPartnerInfo(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $data = Db::name('super_partner')
            ->alias('s')
            ->join('user_manage u', 'u.id = s.uid', 'LEFT')
            ->where('s.id', $superPartnerId)
            ->field('u.id,u.headimgurl,u.xingming,u.code,u.tel,u.sex,u.weixin,u.shengri,u.province,u.city,u.alipay_id,s.real_name,s.id_no,s.id_front_img,s.id_back_img,s.id_hand_img,s.withdraw_password,s.password')
            ->find();
        $data['check_time'] = Db::name('partner_check_log')
            ->where('partner_id',$superPartnerId)
            ->where('partner_type',1)
            ->where('check_status',1)
            ->where('check_type',1)
            ->value('check_time');
        if (!empty($data['id_front_img']) && !empty($data['id_back_img']) && !empty($data['id_hand_img'])){
            $data['check_img'] = 1;
        } else {
            $data['check_img'] = 0;
        }
        if (!empty($data['password'])){
            $data['check_pass'] = 1;
        } else {
            $data['check_pass'] = 0;
        }
        if (!empty($data['withdraw_password'])){
            $data['check_withdraw_pass'] = 1;
        } else {
            $data['check_withdraw_pass'] = 0;
        }
        if (!empty($data['alipay_id'])){
            $data['check_alipay_id'] = 1;
        } else {
            $data['check_alipay_id'] = 0;
        }
        return CommonService::success($data);
    }

    /**
     *超级合伙人资料修改
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function superPartnerEdit(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $validate = Validate::make([
            'id|用户id' => 'require|number',
            'xingming|姓名' => 'require',
            'sex|性别' => 'require|number',
            'weixin|微信号' => 'require',
            'shengri|生日' => 'require',
            'province|省份' => 'require',
            'city|城市' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        if (!empty($requestData['id'])){
            $uid = Db::name('super_partner')->where('id',$superPartnerId)->field('uid')->find();
            if ($uid['uid'] != $requestData['id']){
                return CommonService::error(1);
            }
        } else {
            return CommonService::error(1);
        }
        Db::startTrans();
        try {
            Db::name('user_manage')->where('id', $requestData['id'])->update([
                'xingming' => $requestData['xingming'],
                'sex' => $requestData['sex'],
                'weixin' => $requestData['weixin'],
                'shengri' => $requestData['shengri'],
                'province' => $requestData['province'],
                'city' => $requestData['city'],
                'payee_name' => $requestData['xingming'],
            ]);
            Db::name('super_partner')->where('id', $superPartnerId)->update([
                'real_name' => $requestData['xingming'],
            ]);
            Db::commit();
            return CommonService::success([],106);
        } catch (\Exception $e) {
            Db::rollback();
            return CommonService::error(0);
        }

    }

    /**
     *超级合伙人密码修改
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function superPartnerPasswordEdit(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = $request->post();
        $validate = Validate::make([
            'password|原密码' => 'require',
            'newPassword|新密码' => 'require',
            'newPasswordTwo|重复新密码' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $data = Db::name('super_partner')
            ->where('id',$superPartnerId)
            ->find();
        if (empty($data)){
            return CommonService::error(1);
        }
        if (md5($requestData['password']) != $data['password']){
            return CommonService::error(2);
        }
        if ($requestData['newPassword'] != $requestData['newPasswordTwo']){
            return CommonService::error(105);
        }
        $result = Db::name('super_partner')->where('id', $superPartnerId)->update([
            'password' => md5($requestData['newPassword']),
        ]);
        if ($result){
            return CommonService::success([],106);
        } else {
            return CommonService::error(0);
        }

    }

    /**
     *验证超级合伙人旧手机号
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkOldTel(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
            'code|验证码' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $userId = Db::name('user_manage')->where('tel', $requestData['tel'])->find();
        $superPartner = Db::name('super_partner')->where('uid', $userId['id'])->find();
        if ($superPartner['id'] != $superPartnerId) {
            return CommonService::error(1);
        }
        if ($requestData['code'] != Cache::get('smsCode' . $requestData['tel'])) {
            return CommonService::error(5);
        }
        $data['payee_name'] = $userId['payee_name'];
        return CommonService::success($data, '验证通过！');
    }

    /**
     *验证超级合伙人新手机号并修改手机号
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkNewTel(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
            'code|验证码' => 'require',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $uid = Db::name('super_partner')->where('id', $superPartnerId)->value('uid');
        $userInfo = Db::name('user_manage')->where('id', $uid)->find();
        if (!$userInfo){
            return CommonService::error(1);
        }
        if ($requestData['code'] != Cache::get('smsCode' . $requestData['tel'])) {
            return CommonService::error(5);
        }
        $result = Db::name('user_manage')->where('id', $userInfo['id'])->update([
            'tel' => $requestData['tel'],
        ]);
        if ($result){
            return CommonService::success([],106);
        } else {
            return CommonService::error(0);
        }
    }

    /**
     *验证支付宝并绑定支付宝号
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function AlipayIdAdd(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'alipay_id|支付宝账户' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        $userId = Db::name('super_partner')->where('id', $superPartnerId)->value('uid');
        if (!$userId){
            return CommonService::error(1);
        }
        $result = Db::name('user_manage')->where('id', $userId)->update([
            'alipay_id' => $requestData['alipay_id'],
        ]);
        if ($result){
            return CommonService::success([],106);
        } else {
            return CommonService::error(0);
        }

    }

    /**
     *设置提现密码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function withdrawPasswordAdd(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'w_password|提现密码' => 'require',
            'w_password1|重复提现密码' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        $superPartnerInfo = Db::name('super_partner')->where('id', $superPartnerId)->find();
        if (!$superPartnerInfo){
            return CommonService::error(1);
        }
        if ($requestData['w_password'] != $requestData['w_password1']){
            return CommonService::error(105);
        }
        $result = Db::name('super_partner')->where('id', $superPartnerId)->update([
            'withdraw_password' => $requestData['w_password'],
        ]);
        if ($result){
            return CommonService::success([],107);
        } else {
            return CommonService::error(0);
        }
    }

    /**
     *授权续费
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
     public function getEmpower(Request $request)
     {
         $superPartnerId = $request->superPartnerId;
         $data = Db::name('super_partner')
             ->alias('s')
             ->join('partner_check_log c', 'c.partner_id = s.id', 'LEFT')
             ->where('s.id', $superPartnerId)
             ->where('s.status','<>',0)
             ->where('c.partner_type',1)
             ->where('c.check_status',1)
             ->where('c.check_type',1)
             ->field('c.check_time,s.expire_time,c.add_time')
             ->find();
         if (empty($data)){
             $data['check_time'] = 0;
             $data['expire_time'] = 0;
             $data['add_time'] = 0;
             $data['expire_day'] = 0;
         }
         $nowTime = time();
         foreach ($data as $key => $value) {
             $data['check_time'] = !empty($data['check_time']) ? $data['check_time'] : 0;
             $data['expire_time'] = !empty($data['expire_time']) ? $data['expire_time'] : 0;
             $data['add_time'] = !empty($data['add_time']) ? $data['add_time'] : 0;
             $data['expire_day'] = !empty($data['expire_time']) ? floor(($data['expire_time'] - $nowTime)/86400) : 0;
         }
         return CommonService::success($data);
     }

    /**
     *会员上级推荐人奖励信息数据
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPartnerInfoRebate(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $superInfo = Db::name('user_manage')
            ->alias('o')
            ->join('super_partner u', 'u.uid=o.id', 'LEFT')
            ->where('u.id', $superPartnerId)
            ->field('u.id,o.nickname,o.code,u.user_one_rebate_percent')
            ->find();
        if (!empty($superInfo)){
            $info = $this->getPartnerInfoMaxPercent($superPartnerId);
            $editLog = $this->getSonpartnerLog($superPartnerId);
            $superInfo['edit_num'] = $editLog['edit_count'];
            $superInfo['max_percent'] = $info['max_percent'];
            $superInfo['now_percent'] = $info['now_percent'];
            $superInfo['max_partner_percent'] = $info['max_partner_percent'] ? $info['max_partner_percent'] : 0;
            $superInfo['max_edit_num'] = 12;
            $superInfo['min_percent'] = 5;
            return CommonService::success($superInfo);
        } else {
            return CommonService::error(1);
        }
    }

    /**
     *修改上级推荐人奖励比例
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public  function partnerMaxPercentEdit(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $minPercent = 5;
        $requestData = request()->post();
        $info = $this->getPartnerInfoMaxPercent($superPartnerId);
        $maxPercent = $info['max_percent'];
        $maxPartnerPercent = Db::name('partner')->where('super_partner_id',$superPartnerId)->field('max(rebate_percent) as max_partner_percent')->find();
        $validate = Validate::make([
            'rebate_percent|奖励比例' => 'require',
        ]);
        if (!$validate->check($requestData)){
            return CommonService::error($validate->getError());
        }
        if ($requestData['rebate_percent'] > $maxPercent || $requestData['rebate_percent'] < 0){
            return CommonService::error('最大可设置比例为！' . $maxPercent);
        }
        if ($requestData['rebate_percent'] < $minPercent){
            return CommonService::error('最小可设置比例为！' . $minPercent);
        }
        if ($requestData['rebate_percent'] > 28 - $maxPartnerPercent['max_partner_percent']){
            return CommonService::error('设置比例超过可设定值！');
        }
        $result = Db::name('super_partner')->where('id', $superPartnerId)->update([
            'user_one_rebate_percent' => $requestData['rebate_percent'],
            'remark' => !empty($requestData['remark']) ? $requestData['remark'] : '',
        ]);
        if (!$result){
            return CommonService::error(0);
        }
        $editNum = $this->getSonpartnerLog($superPartnerId);;
        if ($editNum['log_count'] < 12 || $editNum['log_count'] >= 0){
            $result1 = Db::name('super_partner_operate_log')->insert([
                'super_partner_id' => $superPartnerId,
                'value' => $requestData['rebate_percent'],
                'type' => 1,
                'time' => time(),
            ]);
            if (!$result1){
                return CommonService::error(0);
            }
        }
        return CommonService::success([],106);
    }
    /*
     * 获取上级推荐人可修改最大奖励比例
     * */
    public function getPartnerInfoMaxPercent($superPartnerId)
    {
        $maxPercent = Db::name('partner')->where('super_partner_id',$superPartnerId)->field('max(rebate_percent) as max_percent')->find();
        $superPercent = Db::name('super_partner')->where('id',$superPartnerId)->field('user_one_rebate_percent')->find();
        $data['now_percent'] = $superPercent['user_one_rebate_percent'];
        $data['max_partner_percent'] = $maxPercent['max_percent'];
        $data['max_percent'] = 28 - $maxPercent['max_percent'];
        return $data;
    }

    /*
     * 获取上级推荐人可修改最大奖励次数
     * */
    public function getSonpartnerLog($superPartnerId)
    {
        $xiaYtime = mktime(0,0,0,1,1,date('Y')+1);
        $logCount = Db::name('super_partner_operate_log')
            ->where('super_partner_id',$superPartnerId)
            ->where('time', '<', $xiaYtime)
            ->count();
        $data['log_count'] = $logCount;
        $data['edit_count'] = 12 - $logCount;
        return $data;
    }

    /**
     *发送验证码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTelSms(Request $request)
    {
        $superPartnerId = $request->superPartnerId;
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $superPartner = Db::name('super_partner')->where('id', $superPartnerId)->find();
        if (!$superPartner){
            return CommonService::error(1);
        }
        $smsCodeTelTime = Cache::get('smsCodeTelTime' . $requestData['tel']);
//        if (!empty($smsCodeTelTime)){
//            return CommonService::error('请勿在60秒内重复发送验证码！');
//        }
        $templateParam['code'] = mt_rand(1000, 9999);
        $send = CommonService::sendSms($requestData['tel'], $templateParam, 'SMS_175535973');
        if ($send) {
            if (Cache::get('sendSmsCount' . $requestData['tel']) <= 0) {
                $time = strtotime(date('Y-m-d')) + 86400 - time();
                Cache::set('sendSmsCount' . $requestData['tel'], 1, $time);
            } else {
                Cache::inc('sendSmsCount' . $requestData['tel'], 1);
            }
            Cache::set('smsCode' . $requestData['tel'], $templateParam['code'], 300);
//            Cache::set('smsCodeTelTime' . $requestData['tel'], time(), 60);
            return CommonService::success('', '验证码已发送！');
        } else {
            return CommonService::error(3);
        }
    }

}